import { validateNull } from '@/libs/validate'

/**
 * 存储localStorage
 */
export const setStore = (params) => {
    let { name, content, type, datetime } = params;
    let obj = {
        dataType: typeof (content),
        content: content,
        type: type,
        datetime: new Date().getTime()
    }
    if (type) window.sessionStorage.setItem(name, JSON.stringify(obj));
    else window.localStorage.setItem(name, JSON.stringify(obj));
};

/**
 * 获取localStorage
 */
export const getStore = (params) => {
    let { name, type } = params;
    let obj = {}, content;
    obj = window.localStorage.getItem(name);
    if (validateNull(obj)) obj = window.sessionStorage.getItem(name);
    if (validateNull(obj)) return;
    obj = JSON.parse(obj);
    if (obj.dataType == 'string') {
        content = obj.content;
    } else if (obj.dataType == 'number') {
        content = Number(obj.content);
    } else if (obj.dataType == 'boolean') {
        content = eval(obj.content);
    } else if (obj.dataType == 'object') {
        content = obj.content;
    }
    return content;
};
/**
 * 删除localStorage
 */
export const removeStore = params => {
    let { name } = params;
    window.localStorage.removeItem(name);
    window.sessionStorage.removeItem(name);
}

/**
 * @param {Array} target 目标数组
 * @param {Array} arr 需要查询的数组
 * @description 判断要查询的数组是否至少有一个元素包含在目标数组中
 */
export const hasOneOf = (target, arr) => {
    return target.some(_ => arr.indexOf(_) > -1)
}

/**
 * 获取uuid
 */
export const getUUID = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
        return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
    })
};

/**
 * 弹出下载框
 * @param {*} saveName
 * @param {*} url
 */
export function download(saveName, url) {
    if (typeof url == 'object' && url instanceof Blob) {
        url = URL.createObjectURL(url); // 创建blob地址
    }
    var aLink = document.createElement('a');
    aLink.href = url;
    aLink.target = '_blank'
    aLink.download = saveName || ''; // HTML5新增的属性，指定保存文件名，可以不要后缀，注意，file:///模式下不会生效
    var event;
    if (window.MouseEvent) {
        event = new MouseEvent('click');
    } else {
        event = document.createEvent('MouseEvents');
        event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    }
    aLink.dispatchEvent(event);
}


/**
 * JSON对象转成QueryString
 * @param {*} json
 */
export const jsonToQueryString = (json) => {
    if (!json) return ''
    return cleanArray(Object.keys(json).map(key => {
        if (json[key] === undefined || json[key] === '' || json[key] === null) return ''
        return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })).join('&')
}
const cleanArray = (actual) => {
    const newArray = []
    for (let i = 0; i < actual.length; i++) {
        if (actual[i]) {
            newArray.push(actual[i])
        }
    }
    return newArray
}



/**
 * 只允许输入金额数字
 * type 为number
 * item 为json对象
 * keyname为键值
 * event为事件对象.两位小数
 */
export const numberic = (item, keyname, event) => {
    var value = item[keyname];
    var zeroFirst = value.indexOf(0);
    var dot = value.indexOf('.');
    var vlen = value.length

    if (value.indexOf('.') == 0) {
        // alert("value.indexOf('.'):"+value.indexOf('.'));
        // alert("请输入合法的数字!");
        item[keyname] = 0;
    }
    if (zeroFirst == 0) {//首位为0,第二位则必须为.
        if (vlen >= 3 && value.indexOf('.') == 1) {
            if (value.length > 4) {
                item[keyname] = value.substr(0, vlen - 1);
                // alert("最多两位小数!");
            } else {
                if (isNaN(Number(value[vlen - 1]))) {
                    item[keyname] = value.substr(0, vlen - 1);
                    // alert("请输入合法的数字!");
                }
            }
        } else if (vlen == 2 && value.indexOf('.') != 1) {
            // alert("请输入小数点！");
            item[keyname] = 0;
        }
    } else {
        if (dot > -1 && dot + 1 != vlen) {//已输入小数点
            if (isNaN(Number(value[vlen - 1]))) {//小数点后只能输入0-9
                item[keyname] = value.substr(0, vlen - 1);
                // alert("请输入合法的数字0-9!");
            } else if (vlen - dot > 2 + 1) {
                item[keyname] = value.substr(0, vlen - 1);
            }
        } else if (dot == -1) {

        }
    }
}


/**
 * 限制输入：整数，非0开头
 */
export const numberic2 = (item, keyname, event) => {
    var value = item[keyname];
    var reg = /^[1-9]\d*$/;
    if (!value.match(reg)) {
        item[keyname] = ''
    } else {
        item[keyname] = value
    }
}

/**
 * 限制输入：非0开头，整数1-100
 */
export const numberic100 = (item, keyname, event) => {
    var value = item[keyname];
    var reg = /^([1-9][0-9]{0,1}|100)$/;
    if (!value.match(reg)) {
        let num = Number(value)
        if (num > 100) {
            item[keyname] = 100
        } else {
            item[keyname] = ''
        }
    } else {
        item[keyname] = value
    }
}
